<template>
  <div id="content" style="width: 100%; height: 100%">
    <!-- <span id="loadProgress">Diocm加载: </span> -->
    <!-- <div ref="canvas" class="image-canvas" oncontextmenu="return false"></div> -->
  </div>
</template>
<script>
import { RenderingEngine, Types, Enums, metaData } from "@cornerstonejs/core"
import cornerstoneDICOMImageLoader from "@cornerstonejs/dicom-image-loader"
import * as cornerstoneTools from "@cornerstonejs/tools"
import htmlSetup from "./htmlSetup"
const {
  PanTool,
  WindowLevelTool,
  StackScrollMouseWheelTool,
  ZoomTool,
  PlanarRotateTool,
  ToolGroupManager,
  Enums: csToolsEnums,
} = cornerstoneTools
const { ViewportType } = Enums
const { MouseBindings } = csToolsEnums

import { initDemo } from "../utils/demo/helpers"
import {
  convertMultiframeImageIds,
  prefetchMetadataInformation,
} from "../utils/demo/helpers/convertMultiframeImageIds"
let viewport
const toolGroupId = "myToolGroup"
export default {
  data() {
    return {}
  },
  methods: {
    async run() {
      await initDemo()

      const { element } = htmlSetup(document)
      const dropZone = document.getElementById("cornerstone-element")
      dropZone.addEventListener("dragover", this.handleDragOver, false)
      dropZone.addEventListener("drop", this.handleFileSelect, false)

      document.getElementById("selectFile").addEventListener("change", (e) => {
        const file = e.target.files[0]
        const imageId =
          cornerstoneDICOMImageLoader.wadouri.fileManager.add(file)
        this.loadAndViewImage(imageId)
      })

      const renderingEngineId = "myRenderingEngine"
      const renderingEngine = new RenderingEngine(renderingEngineId)

      // Create a stack viewport
      const viewportId = "CT_STACK"
      const viewportInput = {
        viewportId,
        type: ViewportType.STACK,
        element,
        defaultOptions: {
          background: [0.2, 0, 0.2],
        },
      }

      renderingEngine.enableElement(viewportInput)
      viewport = renderingEngine.getViewport(viewportId)

      cornerstoneTools.addTool(PanTool)
      cornerstoneTools.addTool(WindowLevelTool)
      cornerstoneTools.addTool(StackScrollMouseWheelTool)
      cornerstoneTools.addTool(ZoomTool)

      const toolGroup = ToolGroupManager.createToolGroup(toolGroupId)

      toolGroup.addTool(WindowLevelTool.toolName)
      toolGroup.addTool(PanTool.toolName)
      toolGroup.addTool(ZoomTool.toolName)
      toolGroup.addTool(StackScrollMouseWheelTool.toolName)

      toolGroup.setToolActive(WindowLevelTool.toolName, {
        bindings: [
          {
            mouseButton: MouseBindings.Primary, // Left Click
          },
        ],
      })
      toolGroup.setToolActive(PanTool.toolName, {
        bindings: [
          {
            mouseButton: MouseBindings.Auxiliary, // Middle Click
          },
        ],
      })
      toolGroup.setToolActive(ZoomTool.toolName, {
        bindings: [
          {
            mouseButton: MouseBindings.Secondary, // Right Click
          },
        ],
      })
      toolGroup.setToolActive(StackScrollMouseWheelTool.toolName)
      toolGroup.addViewport(viewportId, renderingEngineId)
    },
    // this function gets called once the user drops the file onto the div
    handleFileSelect(evt) {
      evt.stopPropagation()
      evt.preventDefault()

      // Get the FileList object that contains the list of files that were dropped
      const files = evt.dataTransfer.files

      // this UI is only built for a single file so just dump the first one
      const file = files[0]
      const imageId = cornerstoneDICOMImageLoader.wadouri.fileManager.add(file)
      loadAndViewImage(imageId)
    },

    handleDragOver(evt) {
      evt.stopPropagation()
      evt.preventDefault()
      evt.dataTransfer.dropEffect = "copy" // Explicitly show this is a copy.
    },

    async loadAndViewImage(imageId) {
      await prefetchMetadataInformation([imageId])
      const stack = convertMultiframeImageIds([imageId])
      console.log("stack:", stack)

      viewport.setStack(stack).then(() => {
        // Set the VOI of the stack
        // viewport.setProperties({ voiRange: ctVoiRange });
        // Render the image
        viewport.render()
        const imageData = viewport.getImageData()

        const {
          pixelRepresentation,
          bitsAllocated,
          bitsStored,
          highBit,
          photometricInterpretation,
        } = metaData.get("imagePixelModule", imageId)

        const voiLutModule = metaData.get("voiLutModule", imageId)

        const sopCommonModule = metaData.get("sopCommonModule", imageId)
        const transferSyntax = metaData.get("transferSyntax", imageId)

        console.log("imageData:", imageData)
        document.getElementById("transfersyntax").innerHTML =
          transferSyntax.transferSyntaxUID
        // document.getElementById('sopclassuid').innerHTML = `${
        //   sopCommonModule.sopClassUID
        // } [${uids[sopCommonModule.sopClassUID]}]`;
        document.getElementById("sopinstanceuid").innerHTML =
          sopCommonModule.sopInstanceUID
        document.getElementById("rows").innerHTML = imageData.dimensions[0]
        document.getElementById("columns").innerHTML = imageData.dimensions[1]
        document.getElementById("spacing").innerHTML =
          imageData.spacing.join("\\")
        document.getElementById("direction").innerHTML = imageData.direction
          .map((x) => Math.round(x * 100) / 100)
          .join(",")

        document.getElementById("origin").innerHTML = imageData.origin
          .map((x) => Math.round(x * 100) / 100)
          .join(",")
        document.getElementById("modality").innerHTML =
          imageData.metadata.Modality

        document.getElementById("pixelrepresentation").innerHTML =
          pixelRepresentation
        document.getElementById("bitsallocated").innerHTML = bitsAllocated
        document.getElementById("bitsstored").innerHTML = bitsStored
        document.getElementById("highbit").innerHTML = highBit
        document.getElementById("photometricinterpretation").innerHTML =
          photometricInterpretation
        document.getElementById("windowcenter").innerHTML =
          voiLutModule.windowCenter
        document.getElementById("windowwidth").innerHTML =
          voiLutModule.windowWidth
      })
    },
    listenForWindowResize() {
      this.$nextTick(() => {
        window.addEventListener(
          "resize",
          this.debounce(this.onWindowResize, 100)
        )
      })
    },
    onWindowResize() {
      cornerstone.resize(this.$refs.canvas, true)
    },
    /*
     * Utility Methods
     *
     */
    debounce(func, wait, immediate) {
      var timeout
      return function () {
        var context = this
        var args = arguments
        var later = function () {
          timeout = null
          if (!immediate) func.apply(context, args)
        }
        var callNow = immediate && !timeout
        clearTimeout(timeout)
        timeout = setTimeout(later, wait)
        if (callNow) func.apply(context, args)
      }
    },
  },
  mounted() {
    // this.$nextTick(() => {
    this.run()
    // })
  },
}
</script>
